<template>
  <el-dialog
    v-model="visible"
    :title="status ? $t('admin.resetPwd') : $t('admin.createAcc')"
    :close-on-click-modal="false"
    :width="lang === 'en' ? '650px' : '600px'"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      style="width: 500px"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <el-form-item
        :label="$t('station.stationNames')"
        prop="stationName"
        style="width: 500px"
      >
        <el-input
          v-model="dataForm.stationName"
          disabled
        />
      </el-form-item>
      <el-form-item
        :label="$t('homes.userName')"
        prop="account"
        style="width: 580px"
      >
        <el-row style="width: 100%">
          <el-col :span="20">
            <el-input
              v-model="dataForm.account"
              maxlength="50"
              show-word-limit
              :disabled="!editAccount"
              @change="checkAccount()"
            />
          </el-col>
          <el-col :span="4">
            <el-button
              v-if="!editAccount"
              icon="EditPen"
              size="small"
              type="text"
              @click="changeAccountInfo()"
            >
              {{ $t('admin.modifyAcc') }}
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        :label="$t('sys.password')"
        prop="password"
        style="width: 500px"
        class="password"
      >
        <el-input
          v-model="dataForm.password"
          v-input-rule
          type="password"
          onkeyup="value=value.replace(/\s+/g,'')"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('sys.confirmPassword')"
        prop="passwordConfirm"
        style="width: 500px"
      >
        <el-input
          v-model="dataForm.passwordConfirm"
          v-input-rule
          type="password"
          onkeyup="value=value.replace(/\s+/g,'')"
          maxlength="20"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { encrypt } from '@/utils/crypto'
import { ElMessage } from 'element-plus'
import { validPassword } from '@/utils/validate'
const emit = defineEmits(['refreshDataList'])
const lang = localStorage.getItem('b2cLang')
// 自定义校验函数
const dataForm = ref({
  account: '',
  password: '',
  passwordConfirm: ''
})
// eslint-disable-next-line no-unused-vars
const validateAccount = (rule, value, callback) => {
  if (!value) {
    callback(new Error($t('home.accNoNull')))
  }
  if (/\W/g.test(value)) {
    callback(new Error($t('admin.canNumberOrLetter')))
  }
  http({
    url: http.adornUrl('/admin/station/checkStationAccount'),
    method: 'get',
    params: http.adornParams({
      stationId: dataForm.value.stationId,
      account: value
    })
  }).then(({ data }) => {
    if (!data) {
      callback(new Error($t('admin.accIsExist')))
    } else {
      callback()
    }
  })
}
// eslint-disable-next-line no-unused-vars
const validatePassword = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('home.pawNoNull')))
  } else if (!validPassword(value)) {
    callback(new Error($t('sys.passwordVerification')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validatePasswordConfirm = (rule, value, callback) => {
  if (dataForm.value.password !== dataForm.value.passwordConfirm) {
    callback(new Error($t('admin.twoPwdIncon')))
  } else {
    callback()
  }
}
const dataRule = {
  account: [
    { required: true, message: $t('admin.stationAccNoNull'), trigger: 'blur' },
    { validator: validateAccount, trigger: 'blur' }
  ],
  password: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  passwordConfirm: [
    { required: true, message: $t('home.pawNoNull'), trigger: 'blur' },
    { validator: validatePasswordConfirm, trigger: 'blur' }
  ]
}
const visible = ref(false)
const dataFormRef = ref(null)
const init = stationId => {
  dataForm.value.stationId = stationId || 0
  visible.value = true
  dataRule.password[0].required = true
  dataRule.passwordConfirm[0].required = true
  nextTick(() => {
    dataFormRef.value.resetFields()
    dataForm.value.account = null
    dataForm.value.password = null
    dataForm.value.passwordConfirm = null
    getDataInfo()
  })
}
// 获取店铺详情数据
const status = ref(true)
const editAccount = ref(true)

const getDataInfo = () => {
  http({
    url: http.adornUrl('/admin/station/info/' + dataForm.value.stationId),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    dataForm.value.password = ''
    status.value = !!data.account
    editAccount.value = !dataForm.value.account
  })
}
const changeAccountInfo = () => {
  editAccount.value = true
}
const checkAccount = () => {
  dataForm.value.account = dataForm.value.account.trim()
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value.validate(valid => {
    if (valid) {
      // encrypt
      const data = JSON.parse(JSON.stringify(dataForm.value))
      data.password = encrypt(data.password)
      data.passwordConfirm = encrypt(data.passwordConfirm)
      http({
        url: http.adornUrl('/admin/station/changeAccountInfo'),
        method: 'put',
        data: http.adornData(data)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}
defineExpose({ init })
</script>
<style lang="scss" scoped>
:deep(.el-button--small) {
  padding-left: 0;
}
.password :deep(.el-form-item__error){
  text-wrap: nowrap;
}
</style>
